<template>
  <view class="create-page">
    <!-- 头部标题 -->
    <view class="page-header">
      <text class="header-title">发布跑腿订单</text>
      <text class="header-subtitle">填写详细信息，快速找到跑腿员</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <u-form :model="form" :rules="rules" ref="uForm" label-width="65" label-position="top">
        <!-- 订单类型 -->
        <view class="form-section">
          <text class="section-title">订单类型</text>
          <u-radio-group 
            v-model="form.order_type" 
            size="large"
            placement="column"
            activeColor="#ff6a74"
          >
            <u-radio 
              v-for="item in orderTypes" 
              :key="item.value" 
              :name="item.value"
              :label="item.label"
              labelSize="16"
              iconSize="16"
              customStyle="margin-bottom: 16rpx"
            >
              <template #icon>
                <view class="type-icon">
                  <u-icon 
                    :name="getTypeIcon(item.value)" 
                    size="22" 
                    color="#c3c3c3"
                  ></u-icon>
                </view>
              </template>
            </u-radio>
          </u-radio-group>
        </view>

        <!-- 订单信息 -->
        <view class="form-section">
          <text class="section-title">订单信息</text>
          <u-form-item label="标题" prop="title" borderBottom>
            <u--input 
              v-model="form.title" 
              placeholder="例如：取快递、送文件、代买奶茶"
              placeholderClass="placeholder-style"
              border="none"
            ></u--input>
          </u-form-item>
          
          <u-form-item label="描述" prop="description" borderBottom>
            <u--input 
              v-model="form.description" 
              type="textarea" 
              placeholder="请详细描述您的需求，如快递公司、物品大小等"
              placeholderClass="placeholder-style"
              height="120"
              border="none"
            ></u--input>
          </u-form-item>
        </view>

        <!-- 位置信息 -->
        <view class="form-section">
          <text class="section-title">位置信息</text>
          <u-form-item label="取件地点" prop="from_location" borderBottom>
            <u--input 
              v-model="form.from_location" 
              placeholder="例如：南门快递站、3号教学楼"
              placeholderClass="placeholder-style"
              border="none"
              @click="chooseLocation('from')"
            >
              <template #suffix>
                <u-icon 
                  name="map" 
                  size="20" 
                  color="#19be6b"
                  @click="chooseLocation('from')"
                ></u-icon>
              </template>
            </u--input>
          </u-form-item>
          
          <u-form-item label="送件地点" prop="to_location" borderBottom>
            <u--input 
              v-model="form.to_location" 
              placeholder="例如：宿舍楼5栋、图书馆"
              placeholderClass="placeholder-style"
              border="none"
              @click="chooseLocation('to')"
            >
              <template #suffix>
                <u-icon 
                  name="map" 
                  size="20" 
                  color="#19be6b"
                  @click="chooseLocation('to')"
                ></u-icon>
              </template>
            </u--input>
          </u-form-item>
        </view>

        <!-- 时间信息 -->
        <view class="form-section">
          <text class="section-title">时间信息</text>
          <u-form-item label="期望完成时间" prop="expect_time" borderBottom>
            <u-datetime-picker 
              v-model="form.expect_time" 
              :minDate="minDate"
              :maxDate="maxDate"
              mode="datetime"
              :formatter="formatter"
              border="none"
            >
              <view class="time-picker">
                <text>{{ formatExpectTime(form.expect_time) ||'请选择时间'}}</text>
                <u-icon name="arrow-right" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </u-form-item>
        </view>

        <!-- 费用信息 -->
        <view class="form-section">
          <text class="section-title">费用信息</text>
          <u-form-item label="跑腿费用" prop="price" borderBottom>
            <u--input 
              v-model="form.price" 
              type="number" 
              placeholder="请输入合理费用"
              placeholderClass="placeholder-style"
              border="none"
            >
              <template #prefix>
                <text class="price-prefix">¥</text>
              </template>
            </u--input>
          </u-form-item>
          
          <u-form-item label="联系电话" prop="contact_phone" borderBottom>
            <u--input 
              v-model="form.contact_phone" 
              type="number" 
              placeholder="请输入您的手机号"
              placeholderClass="placeholder-style"
              border="none"
            ></u--input>
          </u-form-item>
        </view>

        <!-- 图片上传 -->
        <view class="form-section">
          <text class="section-title">上传图片</text>
          <text class="section-tip">(可选，最多3张，有助于跑腿员识别)</text>
          <u-upload 
            :fileList="fileList"
            @afterRead="afterRead"
            @delete="deletePic"
            :maxCount="3"
            :previewFullImage="true"
            multiple
            uploadText="上传图片"
            width="160"
            height="160"
            :deletable="true"
            :showUploadList="true"
          ></u-upload>
        </view>
      </u-form>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="price-preview">
        <text class="price-label">跑腿费用：</text>
        <text class="price-value">¥{{ form.price || '0.00' }}</text>
      </view>
      <u-button 
        type="success" 
        shape="circle"
        @click="submitForm"
        :loading="submitting"
        :customStyle="{
          width: '200rpx',
          height: '80rpx',
          fontSize: '32rpx'
        }"
      >
        发布订单
      </u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        order_type: 1,
        title: '',
        description: '',
        from_location: '',
        to_location: '',
        expect_time: Date.now() + 3600000, // 默认1小时后
        price: '',
        contact_phone: '',
        images: []
      },
      rules: {
        order_type: [
          { required: true, message: '请选择订单类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入订单标题', trigger: 'blur' },
          { min: 5, max: 50, message: '长度在5到50个字符', trigger: 'blur' }
        ],
        from_location: [
          { required: true, message: '请输入取件地点', trigger: 'blur' }
        ],
        to_location: [
          { required: true, message: '请输入送件地点', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入跑腿费用', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ],
        contact_phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      orderTypes: [
        { label: '取件服务', value: 1 },
        { label: '送件服务', value: 2 },
        { label: '代购服务', value: 3 },
        { label: '其他服务', value: 4 }
      ],
      minDate: Date.now(),
      maxDate: Date.now() + 7 * 24 * 3600000, // 一周后
      fileList: [],
      submitting: false,
      formatter: (type, value) => {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        if (type === 'hour') {
          return `${value}时`
        }
        if (type === 'minute') {
          return `${value}分`
        }
        return value
      }
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    getTypeIcon(type) {
      const iconMap = {
        1: 'coupon-fill',
        2: 'car-fill',
        3: 'shopping-cart-fill',
        4: 'more-circle-fill'
      }
      return iconMap[type] || 'more-circle-fill'
    },
    
    chooseLocation(type) {
      uni.chooseLocation({
        success: (res) => {
          if (type === 'from') {
            this.form.from_location = res.name
          } else {
            this.form.to_location = res.name
          }
        }
      })
    },
    
    formatExpectTime(timestamp) {
      if (!timestamp) return '请选择时间'
      const date = new Date(timestamp)
      return this.$u.timeFormat(date, 'yyyy年mm月dd日 hh:MM')
    },
    
    afterRead(event) {
      const files = event.file
      files.forEach(file => {
        this.uploadFile(file)
      })
    },
    
    async uploadFile(file) {
      try {
        this.$u.toast('上传中...', { icon: 'loading' })
        const res = await this.$u.upload('/api/upload/image', {
          file: file,
          name: 'file'
        })
        
        if (res.code === 200) {
          this.form.images.push(res.data.url)
          this.fileList.push({ url: res.data.url })
          this.$u.toast('上传成功')
        }
      } catch (error) {
        this.$u.toast('上传失败')
      }
    },
    
    deletePic(event) {
      this.form.images.splice(event.index, 1)
      this.fileList.splice(event.index, 1)
    },
    
    async submitForm() {
      try {
        this.submitting = true
        await this.$refs.uForm.validate()
        
        const params = {
          ...this.form,
          expect_time: this.$u.timeFormat(this.form.expect_time, 'yyyy-mm-dd hh:MM'),
          images: this.form.images
        }
        
        const res = await this.$u.api.errandOrder.create(params)
        
        if (res.code === 200) {
          this.$u.toast('订单创建成功', { icon: 'success' })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        if (error.message) {
          this.$u.toast(error.message)
        } else {
          this.$u.toast('订单创建失败')
        }
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.create-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 140rpx;
}

.page-header {
  padding: 40rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom-left-radius: 24rpx;
  border-bottom-right-radius: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .header-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 10rpx;
  }
  
  .header-subtitle {
    font-size: 26rpx;
    color: #999;
  }
}

.form-container {
  padding: 0 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .section-tip {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 20rpx;
    display: block;
  }
}

.type-icon {
  width: 40rpx;
  height: 40rpx;
  
  border-radius: 50%;
  background-color: rgba(25, 190, 107, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  // margin-right: 16rpx;
}

.time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 16rpx 0;
}

.placeholder-style {
  color: #c0c4cc !important;
}

.price-prefix {
  color: #ff5a5f;
  font-weight: bold;
  margin-right: 10rpx;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .price-preview {
    display: flex;
    align-items: center;
    
    .price-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .price-value {
      font-size: 36rpx;
      font-weight: bold;
      color: #ff5a5f;
    }
  }
}

/* 自定义uview组件样式 */
::v-deep .u-form-item {
  padding: 24rpx 0 !important;
  
  &__body {
    padding: 0 !important;
  }
  
  &__body__right__content {
    border: none !important;
    padding: 0 !important;
  }
}

::v-deep .u-radio {
  padding: 16rpx 0 !important;
}
</style>